<template>
  <div class="login-container">
    <!-- 左侧登录表单区域 -->
    <div class="login-left">
      <div class="login-form-wrapper">
        <!-- Logo和标题 -->
        <div class="login-header">
          <div class="logo">
            <div class="logo-icon">🏦</div>
            <h1 class="login-title">贷后管理系统</h1>
          </div>
          <p class="welcome-text">欢迎回来 👋</p>
          <p class="login-subtitle">请选择机构并登录以开始管理您的案件</p>
        </div>

        <!-- 登录表单 -->
        <a-form :model="loginForm" :rules="loginRules" @finish="handleLogin" class="login-form" layout="vertical">
          <!-- 机构选择 -->
          <a-form-item label="选择机构" name="organizationId">
            <a-select 
              v-model:value="loginForm.organizationId" 
              placeholder="请选择机构" 
              :size="size" 
              :disabled="loading"
              @change="handleOrganizationChange" 
              show-search 
              :filter-option="filterOrganizationOption"
              class="form-input"
            >
              <a-select-option v-for="org in organizations" :key="org.account" :value="org.account">
                {{ org.name }} ({{ org.account }})
              </a-select-option>
            </a-select>
          </a-form-item>

          <!-- 账户 -->
          <a-form-item label="账户" name="accountNo">
            <a-input 
              v-model:value="loginForm.accountNo" 
              placeholder="账户将自动填充" 
              :size="size" 
              :disabled="true"
              class="form-input"
            >
              <template #prefix>
                <UserOutlined class="input-icon" />
              </template>
            </a-input>
          </a-form-item>

          <!-- 密码 -->
          <a-form-item label="密码" name="pwd">
            <a-input-password 
              v-model:value="loginForm.pwd" 
              placeholder="密码将自动填充" 
              :size="size" 
              :disabled="true"
              class="form-input"
            >
              <template #prefix>
                <LockOutlined class="input-icon" />
              </template>
            </a-input-password>
          </a-form-item>

          <!-- 验证码显示 -->
          <a-form-item label="验证码">
            <div class="totp-display">
              <div class="totp-code">{{ currentTOTPCode }}</div>
              <div class="countdown">剩余: {{ countdown }}s</div>
            </div>
          </a-form-item>

          <!-- 登录按钮 -->
          <a-form-item>
            <a-button 
              type="primary" 
              html-type="submit" 
              :size="size" 
              :loading="loading" 
              :block="true"
              class="login-button"
            >
              {{ loading ? '登录中...' : '登录' }}
            </a-button>
          </a-form-item>
        </a-form>

        <!-- 底部信息 -->
        <div class="login-footer">
          <p class="copyright">© 2024 贷后管理系统. All rights reserved.</p>
        </div>
      </div>
    </div>

    <!-- 右侧装饰区域 -->
    <div class="login-right">
      <div class="decoration-content">
        <div class="decoration-graphic">
          <div class="graphic-element element-1"></div>
          <div class="graphic-element element-2"></div>
          <div class="graphic-element element-3"></div>
          <div class="graphic-element element-4"></div>
          <div class="graphic-element element-5"></div>
        </div>
        <div class="decoration-text">
          <h2 class="decoration-title">开箱即用的贷后案件管理系统</h2>
          <p class="decoration-subtitle">工程化、高性能、现代化的案件管理平台</p>
          <div class="feature-list">
            <div class="feature-item">
              <span class="feature-icon">📊</span>
              <span>案件数据管理</span>
            </div>
            <div class="feature-item">
              <span class="feature-icon">🔐</span>
              <span>安全权限控制</span>
            </div>
            <div class="feature-item">
              <span class="feature-icon">⚡</span>
              <span>高效工作流程</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import {
  UserOutlined,
  LockOutlined
} from '@ant-design/icons-vue';
import { loginSms } from '../server/api';
import { useUserStore } from '../store/user';
import { organizationManager } from '../config/organization-manager';
import type { Organization } from '../config/organizations.env';
// @ts-ignore
import '../utils/crypto-js.js';
import { authenticator } from 'otplib';

// 路由实例
const router = useRouter();
const userStore = useUserStore();

// 全局类型声明
declare global {
  var CryptoJS: any;
  var global: any;
}

// 获取CryptoJS实例
const getCryptoJS = () => {
  if (typeof globalThis !== 'undefined' && (globalThis as any).CryptoJS) {
    return (globalThis as any).CryptoJS;
  }
  if (typeof window !== 'undefined' && (window as any).CryptoJS) {
    return (window as any).CryptoJS;
  }
  if (typeof global !== 'undefined' && (global as any).CryptoJS) {
    return (global as any).CryptoJS;
  }
  throw new Error('CryptoJS未加载，请检查crypto-js.js是否正确导入');
};

// 组件状态
const size = ref<'small' | 'middle' | 'large'>('large');
const loading = ref(false);

// 机构列表
const organizations = ref<Organization[]>([]);

// TOTP相关
const currentTOTPCode = ref('');
const countdown = ref(30);
const totpInterval = ref<number | null>(null);
const countdownInterval = ref<number | null>(null);
const MY_SECRET = 'vuixppgt3kx3fbtjp2pzgfzzccxqkv7q';

// 登录表单数据
const loginForm = reactive({
  organizationId: '',
  accountNo: '',
  pwd: ''
});

// 表单验证规则
const loginRules = {
  organizationId: [
    { required: true, message: '请选择机构', trigger: 'change' }
  ],
  accountNo: [
    { required: true, message: '账户不能为空', trigger: 'blur' }
  ],
  pwd: [
    { required: true, message: '密码不能为空', trigger: 'blur' }
  ]
};

// 更新TOTP验证码
const updateTOTP = async () => {
  try {
    const code = authenticator.generate(MY_SECRET);
    const now = new Date();
    console.log(`[${now.toLocaleTimeString()}] TOTP验证码更新: ${code}`);
    currentTOTPCode.value = code;
  } catch (error) {
    console.error('生成TOTP验证码失败:', error);
    currentTOTPCode.value = '错误: ' + (error as Error).message;
  }
};

// 启动TOTP定时器
const startTOTPTimer = () => {
  console.log('启动TOTP定时器...');
  
  // 清除现有定时器
  stopTOTPTimer();

  // 立即更新一次验证码
  updateTOTP();

  // 设置统一的定时器（每秒检查）
  countdownInterval.value = setInterval(() => {
    const now = Date.now();
    const remaining = 30 - (Math.floor(now / 1000) % 30);
    countdown.value = remaining;
    
    // 当倒计时到0秒时更新验证码
    if (remaining === 30) {
      console.log('倒计时归零，更新验证码');
      updateTOTP();
    }
    
    // 调试信息：每5秒输出一次倒计时
    if (remaining % 5 === 0) {
      console.log(`[${new Date().toLocaleTimeString()}] TOTP倒计时: ${remaining}s`);
    }
  }, 1000);
  
  console.log('TOTP定时器启动完成');
};

// 停止TOTP定时器
const stopTOTPTimer = () => {
  console.log('停止TOTP定时器...');
  
  if (totpInterval.value) {
    clearInterval(totpInterval.value);
    totpInterval.value = null;
    console.log('验证码更新定时器已清除');
  }
  if (countdownInterval.value) {
    clearInterval(countdownInterval.value);
    countdownInterval.value = null;
    console.log('倒计时定时器已清除');
  }
  
  console.log('TOTP定时器停止完成');
};

// 机构选择变化处理
const handleOrganizationChange = (account: string) => {
  const selectedOrg = organizations.value.find(org => org.account === account);
  if (selectedOrg) {
    loginForm.accountNo = selectedOrg.account;
    loginForm.pwd = selectedOrg.password;
  }
};

// 机构搜索过滤
const filterOrganizationOption = (input: string, option: any) => {
  const org = organizations.value.find(o => o.account === option.value);
  if (!org) return false;
  return org.name.toLowerCase().includes(input.toLowerCase()) ||
    org.account.toLowerCase().includes(input.toLowerCase());
};

// 处理登录
const handleLogin = async (values: any) => {
  try {
    loading.value = true;

    const selectedOrg = organizations.value.find(org => org.account === values.organizationId);
    if (!selectedOrg) {
      throw new Error('请选择有效的机构');
    }

    // 使用当前TOTP验证码
    const code = currentTOTPCode.value;
    if (!code || code.startsWith('错误:')) {
      throw new Error('TOTP验证码无效，请刷新页面重试');
    }

    // 加密密码
    const encryptedPassword = getCryptoJS().MD5(selectedOrg.password).toString();
    console.log('密码加密:', { original: selectedOrg.password, encrypted: encryptedPassword });
    console.log('使用验证码:', code);

    // 调用登录接口
    const response = await loginSms({
      accountNo: selectedOrg.account,
      pwd: encryptedPassword,
      code: code,
      tsToken: null
    });

    console.log('登录接口返回:', response);

    // @ts-ignore
    if (response.code === '200' && response.success) {
      // 登录成功，停止TOTP定时器
      stopTOTPTimer();
      console.log('登录成功:', response.result);

      // 实现完整的登录流程：设置tsToken，重新获取个人信息
      await handleOrganizationLogin(response.result);

      message.success('登录成功');
    } else {
      throw new Error(response.message || '登录失败');
    }

  } catch (error) {
    console.error('登录失败:', error);
    const errorMessage = error instanceof Error ? error.message : '登录失败，请重试';
    message.error(errorMessage);
  } finally {
    loading.value = false;
  }
};

// 处理机构登录后的完整流程
const handleOrganizationLogin = async (loginData: any) => {
  try {
    console.log('开始处理机构登录流程...');

    // 1. 设置tsToken到localStorage，用于API请求
    localStorage.setItem('tsToken', loginData.tsToken);
    console.log('tsToken已设置:', loginData.tsToken);

    // 2. 调用userStore的login方法，实现完整的登录流程
    await userStore.login({ tsToken: loginData.tsToken });

    console.log('机构登录流程完成，用户状态已更新');
    console.log('当前用户信息:', userStore.userInfo);
    console.log('当前tsToken:', userStore.tsToken);
    console.log('登录状态:', userStore.isLoggedIn);

    // 3. 跳转到首页
    console.log('跳转到首页...');
    router.push('/');

  } catch (error) {
    console.error('机构登录流程失败:', error);
    // 如果获取用户信息失败，清除可能已保存的数据
    localStorage.removeItem('tsToken');
    localStorage.removeItem('userInfo');
    throw error;
  }
};

// 组件挂载时
onMounted(() => {
  // 加载机构列表
  organizations.value = organizationManager.getAllOrganizations();

  // 启动TOTP定时器
  console.log('组件挂载，启动TOTP定时器');
  startTOTPTimer();
});

// 组件卸载时
onUnmounted(() => {
  console.log('组件卸载，停止TOTP定时器');
  stopTOTPTimer();
});
</script>

<style scoped>
/* 主容器 - 左右分栏布局 */
.login-container {
  min-height: 100vh;
  display: flex;
  background: #f8fafc;
}

/* 左侧登录表单区域 */
.login-left {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  background: #ffffff;
  position: relative;
}

.login-form-wrapper {
  width: 100%;
  max-width: 420px;
  padding: 0;
}

/* Logo和标题区域 */
.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 24px;
}

.logo-icon {
  font-size: 32px;
  margin-right: 12px;
}

.login-title {
  font-size: 32px;
  font-weight: 700;
  color: #1a1a1a;
  margin: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.welcome-text {
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 8px 0;
}

.login-subtitle {
  font-size: 16px;
  color: #666;
  margin: 0;
  line-height: 1.5;
}

/* 表单样式 */
.login-form {
  margin-bottom: 0;
}

.form-input {
  height: 50px;
  border-radius: 8px;
  border: 1px solid #e1e5e9;
  transition: all 0.3s ease;
}

.form-input:hover {
  border-color: #667eea;
}

.form-input:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

/* 修复机构选择下拉框双重边框问题 */
.login-form :deep(.ant-select.form-input .ant-select-selector) {
  border: none !important;
  box-shadow: none !important;
  height: 48px;
  border-radius: 8px;
}

.login-form :deep(.ant-select.form-input .ant-select-selector:hover) {
  border: none !important;
  box-shadow: none !important;
}

.login-form :deep(.ant-select.form-input.ant-select-focused .ant-select-selector) {
  border: none !important;
  box-shadow: none !important;
}

/* 验证码显示样式 */
.totp-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  max-width: 240px;
  margin: 0 auto;
  padding: 20px 24px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border: 1px solid #e1e5e9;
  border-radius: 12px;
  font-family: 'Courier New', monospace;
  position: relative;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.totp-code {
  font-size: 24px;
  font-weight: bold;
  color: #667eea;
  letter-spacing: 3px;
  margin-bottom: 8px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.countdown {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
}

.input-icon {
  color: #94a3b8;
  font-size: 16px;
}

/* 登录按钮 */
.login-button {
  height: 52px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 12px;
  margin-top: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
}

.login-button:active {
  transform: translateY(0);
}

/* 底部信息 */
.login-footer {
  text-align: center;
  margin-top: 32px;
}

.copyright {
  font-size: 14px;
  color: #94a3b8;
  margin: 0;
}

/* 右侧装饰区域 */
.login-right {
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.decoration-content {
  text-align: center;
  color: white;
  z-index: 2;
  position: relative;
}

.decoration-graphic {
  position: relative;
  width: 300px;
  height: 300px;
  margin: 0 auto 40px;
}

.graphic-element {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  animation: float 6s ease-in-out infinite;
}

.element-1 {
  width: 80px;
  height: 80px;
  top: 20px;
  left: 50px;
  animation-delay: 0s;
}

.element-2 {
  width: 120px;
  height: 120px;
  top: 60px;
  right: 40px;
  animation-delay: 1s;
}

.element-3 {
  width: 60px;
  height: 60px;
  bottom: 80px;
  left: 30px;
  animation-delay: 2s;
}

.element-4 {
  width: 100px;
  height: 100px;
  bottom: 40px;
  right: 60px;
  animation-delay: 3s;
}

.element-5 {
  width: 40px;
  height: 40px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  animation-delay: 4s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-20px);
  }
}

.decoration-title {
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 16px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.decoration-subtitle {
  font-size: 18px;
  margin: 0 0 32px 0;
  opacity: 0.9;
  line-height: 1.6;
}

.feature-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  align-items: center;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 16px;
  font-weight: 500;
  background: rgba(255, 255, 255, 0.1);
  padding: 12px 24px;
  border-radius: 24px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.feature-icon {
  font-size: 20px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .login-right {
    display: none;
  }
  
  .login-left {
    flex: 1;
  }
}

@media (max-width: 768px) {
  .login-container {
    flex-direction: column;
  }
  
  .login-left {
    padding: 20px;
  }
  
  .login-title {
    font-size: 28px;
  }
  
  .welcome-text {
    font-size: 20px;
  }
  
  .decoration-title {
    font-size: 24px;
  }
  
  .decoration-subtitle {
    font-size: 16px;
  }
}

@media (max-width: 480px) {
  .login-form-wrapper {
    max-width: 100%;
  }
  
  .login-title {
    font-size: 24px;
  }
  
  .welcome-text {
    font-size: 18px;
  }
  
  .totp-display {
    max-width: 100%;
    padding: 16px 20px;
  }
  
  .totp-code {
    font-size: 20px;
  }
}
</style>
